var app = angular.module('webapp');

app.controller('UserController', ['$scope','UserService', UserController]);

app.directive('fileModel',['$parse',function($parse){
    return {
        name:'A',
        scope:{

        },
        replace:true,
        template:'<input id="fileId1" fileModel="myFile" type="file" accept="image/*" name="file" />',
        link:function(scope, element , attrs , ngModel){
            var model = $parse(attrs.fileModel);
            element.bind('change', function(event){
                scope.file = (event.srcElement || event.target).files[0];
                var imageType = /image.*/;
                //如果是文件类型是图片
                if (scope.file.type.match(imageType)) {
                    //创建img标签写入userHead
                    var img = document.createElement("img");
                    img.classList.add("obj");
                    img.file = scope.file;
                    $('.userHead').empty().html(img);

                    //实例化一个文件对象FileReader
                    var reader = new FileReader();
                    //onload成功读取
                    reader.onload = (function(aImg){
                        return function(e){
                            aImg.src = e.target.result;
                        };
                    })(img);
                    //将文件读取为DataURL
                    reader.readAsDataURL(scope.file);
                }
            });
        }
    }
}]);

app.directive('userEdit', ['UserService',function(UserService){
    return {
        name: 'E',
        scope: {
            ngModel:'=',
            ngOperate:'=',
            ngRolelist:'=',
            ngUserrole:'=',
            ngOpertype:'='
        },
        replace:true,
        templateUrl:'../../views/system/user_edit.tpl',
        link: function($scope, iElm, iAttrs, controller) {
            $scope.sexSelected = '';
            $scope.sexData ={
                "0":{ID:'0',NAME:'男'},
                "1":{ID:'1',NAME:'女'}
            };
            $scope.closeUserEdit = function(){
                $scope.$parent.eShow = false;
            };
            $scope.cancelEdit = function(){
                $scope.ngOpertype = $scope.ngOpertype!=0 ? 2 : $scope.closeUserEdit();
            };
            $scope.removeUser = function(){
                $('#deleteModal').modal('show');
                $('#sureDel').unbind('click').click(function(){
                    UserService.removeUser(scope.ngModel,function(){
                        $.toast("删除成功");
                        $scope.$parent.loadUser();
                        $scope.$parent.eShow = false;
                    },function(err){
                        alert(err);
                    });
                });
            };
            $scope.saveUser=function(){
                var saveData = new FormData();
                saveData.append("headfile",document.getElementById('fileId1').files[0]);
                for(var i in $scope.ngModel){
                    var model = $scope.ngModel[i];
                    if(i!='$$hashKey'){
                        saveData.append(i,model);
                    }
                }
                UserService.saveUser(saveData,function(result){
                    $.toast("保存成功");
                    $scope.$parent.loadUser();
                    $scope.$parent.eShow = false;
                },function(err){
                    console.log(err);
                });
            };
            $scope.editUser = function(){
                $scope.ngOpertype = 1;
            };

            $scope.$watch('ngOpertype',function(value){
                if(value == 0 || value == 1){
                    var roleValues = [] , roleDisplayValues=[];
                    for(var i in $scope.ngRolelist){
                        var obj = $scope.ngRolelist[i];
                        roleDisplayValues.push(obj.NAME);
                        roleValues.push(obj.ID);
                    }
                    setTimeout(function(){
                        $("#city-picker").cityPicker({
                            toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">选择地址</h1>\
                            </header>',
                            inputReadOnly:true,
                            onClose:function(){
                                $scope.ngModel.ADDRESS = $("#city-picker").val();
                            }
                          });

                        $('#birthTime').calendar({
                            inputReadOnly:true,
                            onClose:function(){
                                $scope.ngModel.BIRTH_TIME = new Date($("#birthTime").val()).getTime();
                            }
                        });

                        $('#roleIpt').picker({
                            toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择角色</h1>\
                              </header>',
                              inputReadOnly:true,
                              formatValue:function(picker, value, displayValue){
                                $scope.ngModel.ROLE_ID = value;
                                return displayValue;
                              },
                              cols:[
                              {
                                textAlign: 'center',
                                values:roleValues,
                                displayValues:roleDisplayValues
                              }
                              ]
                        });

                        $('#sexIpt').picker({
                            toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择性别</h1>\
                              </header>',
                              inputReadOnly:true,
                              formatValue:function(picker, value, displayValue){
                                $scope.ngModel.SEX = value;
                                return displayValue;
                              },
                              cols:[
                              {
                                textAlign: 'center',
                                values:[0,1],
                                displayValues:["男","女"]
                              }
                              ]
                        });
                    },500);
                }
            });
        }
    };
}]);
function UserController($scope,UserService){
	
    $scope.userModel = {
        ADDRESS: "",AVATAR:"",BIRTH_TIME:"",CELL_PHONE:"",DATA_BIRTH:"",ID:"",LOGIN_STATUS:"",
        OVER_LOGIN_TIME:"",PASSWORD:"",REAL_NAME:"",REGISTRY_TIME:"",ROLE_ID:"",SEX:"",USER_NAME:""
    };
    $scope.menuId = document.getElementById('menuId').value;
    $scope.eShow = false; //编辑块与列表的显示切换
    $scope.opertype = -1; //记录操作类型 0新增 1编辑 2查看
    $scope.searshUserName = ''; //搜索框值
    $scope.userRole = null; //当前查看用的角色对象
    $scope.data = {
        currentPage:1,
        pageSize:10,
        keyWord:$scope.searshUserName
    };
    $scope.warpperStyle = {
        'min-height':(document.body.scrollHeight||document.documentElement.scrollHeight - 38)+'px'
    };

    //菜单功能配置    
    $scope.functions = [
        {ALT:'新增用户',fn:'addUser',class:'glyphicon glyphicon-plus'}
    ];

    $scope.$watch('searshUserName',function(){
        $scope.loadUser();
    });
    //加载权限
    $scope.loadPower = function(){
        UserService.getPower({menuId:$scope.menuId}).then(function(result){
            if(result && result.length>0){
                var power = result[0];
                var ot = power.OPERATE_TYPE.split(',');
                $scope.roleOperateType = {};
                for(var i in ot){
                    $scope.roleOperateType['r'+ot[i]] = ot[i];
                }
            }
        },function(err){

        });
    };
    $scope.loadPower();
    $scope.loadUser = function(){
        $.showPreloader();
        $scope.data.keyWord = $scope.searshUserName;
        UserService.getUserAll($scope.data).then(function(res){
            $scope.userList = res.result;
            $scope.role = res.role;
            $scope.roleList = res.roleList;
            $.hidePreloader();
        },function(err){
            console.log(err);
        });
    };
    //查看详情
    $scope.userDetail = function(model){
        $scope.opertype = 2;
        for(var m in $scope.roleList){
            var rl = $scope.roleList[m];
            if(rl.ID == model.ROLE_ID){
                $scope.userRole = rl;
            }
        }
        for(var i in model){
            $scope.userModel[i] = model[i];
        }
        $scope.eShow = true;
    };
    //新增
    $scope.addUser = function(){
        $scope.opertype = 0;
        for(var i in $scope.userModel){
            $scope.userModel[i] = "";
        }
        $scope.eShow = true;
    };
    //编辑
    $scope.editUser = function(){
        $scope.opertype = 1;
    };
    $scope.funFactroy = function($event){
        var _par = angular.element($event.target);
        var funName = _par[0].getAttribute('ck');
        $scope[funName]();
    };
}